// 研发网测试环境对应的配置信息

$.ajaxSetup({
    beforeSend: function(xhr) {},
    // dataFilter: function (data, type) {
    // },
    complete: function(xhr, status) {
        if (xhr.status == "9981") {
        // if (xhr.status == "9981" || xhr.status == '0') {
            mui.toast('当前用户会话过期,将要自动跳转登录页面!', {
                duration: 'long',
                type: 'div'
            })
            setTimeout(function() {
                $(location).attr("href", "../index.html");
            }, 1500)

        } else if (xhr.status == "200") {

        } else {
            // mui.toast("请求异常，请稍后再试", {
            //     duration: 'long',
            //     type: 'div'
            // })
        }
    }
});


let vconsole = new VConsole()
vconsole.showSwitch();

// 测试环境（uat开发需打开此模式，生产环境注释 。相邻//中间代码）
let corpid = "wwf14c1c1c8458dc0b";
let isc_appid = "a5edcee2ff464051a22a2133bc4d1485"; //账户 Isc AppId
// let isc_appid = "fbc7f60a700741d5895567c2e70dce8a"; //账户 Isc AppId
let sURLgetWxCode = "http://27.10.115.223:80/connect/oauth2/authorize?"
let appid = "wwf14c1c1c8458dc0b" // 写死
let encodeURIComponentUrl = "zipapp://local.host/index.html"
let magentid = '1000469'
// let magentid = '1003596'
let sURLgetIscToken = "http://27.10.115.223:10443/eeee/identity/getAuthTicketByWechatCode"
let isFlag = true; //true 开发模式 false 生产
let isFlagOne = false; //true 脱敏 fasle不托
// var localUrlLink = "http://27.196.108.106:18701"
var localUrlLink = "http://27.196.39.6:18701"
let urlLinkIp = "60.28.54.50" //交互平台ip  开发iscp 生产 127.0.0.1
let urlServeruser = "buser" //用户id  写死 不管
let urlServerappid = "newsgcc" //应用id  不管 后续提供
// let urlLocalip = "172.20.8.196" //本地ip 不管 后续提供
    // 

let nonceStr = "AMQGnmTMzhJetshY" // 必填，生成签名的随机串
let signature = "fb9f560a9b4824f7db3525926994010de74ea055" // 必填，签名，见附录1
let urlLinkPort = "20084" //交互平台port   写死 不管
let urlLocalport = "18080" //本地port 不管 后续提供
let timestamp = Date.now();
let userId;
let userName;
let unitId;
var homeKey = "dc20e223eaa8bd04f65c7859e5fb7073b7a04cb670326650db165a7e4500ef42"

var iscp = {
    port: ''
}
let iscp_port
if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
} else {
    iscp_port = ""
}
let toMail = "" //公共邮箱
let urlMyLink = urlLinkIp + ':' + urlLinkPort //链路标识 60.28.54.50:20084
let jsApiList = []; //需要使用的功能接口


//  开发环境不走 安全交互
function createISCPLink(int) {
    $("#showP").html(" 正在建立安全连接...")
    $.getScript("../js/jweixin-sgccigw-1.0.0" /*"js/jweixin-1.0.0.js"*/ , function() {
        'use strict';
        wx.ready(function() {});
        jsApiList = [
            "ext_Net_Upload",
            "getLocalResPath",
            "ext_FileManager_Information",
            'ext_ISCP_Init',
            'ext_ISCP_ConnectService',
            'ext_ISCP_GetLocalPort',
            'ext_ISCP_Close',
            'ext_ISCP_Status',
            'ext_Popover_Open',
            'ext_Popover_Close',
            "multiWindows_open",
            "multiWindows_close",
            "multiWindows_startWidget",
            "multiWindows_finishWidget",
            "multiWindows_subscribe",
            "multiWindows_publish",
            'shareWechatMessage',
            'onMenuShareTimeline',

            'chooseImage',
            'getLocalImgData',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'previewFile',

            'startRecord',
            'stopRecord',
            'onVoiceRecordEnd',
            'playVoice',
            'playVoice',
            'stopVoice',
            'onVoicePlayEnd',
            'startRecordVoiceBuffer',
            'onRecordBufferReceived',
            'stopRecordVoiceBuffer',
            'uploadVoice',
            'downloadVoice',
            'translateVoice',

            'setClipboardData',
            'getClipboardData',

            'openLocation',
            'startAutoLBS',
            'stopAutoLBS',
            'onLocationChange',

            'onHistoryBack',
            'closeWindow',
            'openUrl',

            'scanQRCode',

            'launch3rdApp',

            'ocr',

            'checkJsApi',
        ];
        wx.config({
            beta: true,  
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: appid, // 必填，政务微信的cropID
            timestamp: '1626832073', // 必填，生成签名的时间戳
            nonceStr: nonceStr, // 必填，生成签名的随机串
            signature: signature, // 必填，签名，见附录1
            jsApiList: jsApiList // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });

        // 初始化
    });
};
// 通用请求接口
function greneralRequest(url,obj) {
    let valueList = {}
    userId = sessionStorage.getItem("userId");
    orgId = sessionStorage.getItem("unitId")
    const timestamp = new Date().getTime() + ""
    const AuthenticationSession = sessionStorage.getItem("Authentication");
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    let data = {
        userId: userId,
        orgId: orgId,
        timestamp: timestamp
      }
     data = Object.assign({},JSON.parse(obj),data)
     data = JSON.stringify(data)
    let sign = sm3(data);
    $.ajax({
        url: localUrlLink + iscp_port + url,
        type: "post",
        async: false, //是否同步，false表示同步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            Authentication: AuthenticationSession,
            sign: sign,
            userId:userId,
            timestamp: timestamp
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")
                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                        // valueList = res.resultValue
                    }
                    valueList = res
                } else {
                    mui.toast(res.resultValue, {
                        duration: 'long',
                        type: 'div'
                    })
                }
            } else {
                mui.toast('完整性校验失败', {
                    duration: 'long',
                    type: 'div'
                })
            }
        },
        error: (e) => {
            mui.toast('请求异常,请稍后再试', {
                duration: 'long',
                type: 'div'
            })
        },

    });
    return valueList
};
function login() {
    var access_token = "";
    let userId = sessionStorage.getItem("userId");
    let data = {
        "userId": userId,
        "timestamp": new Date().getTime() + "" //时间戳
    }
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    data = JSON.stringify(data)
    let sign = sm3(data);
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    $.ajax({
        url: localUrlLink + iscp_port + "/pxapi/oauth/getToken",
        type: "post",
        async: false, //是否同步，false表示同步请求 true表示异步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            sign: sign,
            Authentication: AuthenticationSession,
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")
                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                        access_token = res.resultValue;
                    }
                } else {
                    $(".curtain").css("display", "none");
                    mui.toast(res.resultValue, {
                        duration: 'long',
                        type: 'div'
                    })
                }
            } else {
                $(".curtain").css("display", "none");
                mui.toast('完整性校验失败', {
                    duration: 'long',
                    type: 'div'
                })
            }
        },
        error: (e) => {
            $(".curtain").css("display", "none");
            mui.toast("请求异常请稍后再试", {
                duration: 'long',
                type: 'div'
            })
        },

    });
    return access_token;
};

function utilFunc(map) {
    var sortMap = function(map, isKeyUpSort) {
        let keys = new Array();
        for (var key of map.keys()) {
            keys.push(key);
        }
        if (isKeyUpSort) {
            keys = keys.sort(function(key1, key2) {
                return key1.localeCompare(key2);
            });
        } else {
            keys = keys.sort(function(key1, key2) {
                return key2.localeCompare(key1);
            });
        }
        let str = "";
        keys.forEach((key) => {
            if (null != map.get(key) && "" != map.get(key)) {
                str = str + key + "=" + map.get(key);
            }
        });
        return str;
    };
    var str = sortMap(map, true);
    let hashData = sm3(str);

    let hashData_last = sm3(hashData);
    hashData_last = hashData_last.substr(0, 5);
    hashData += hashData_last;
    return hashData;
};
// 初始化
function iscpInit() {
    wx.invoke("ext_ISCP_Init", {
        data: {
            iscpIP: urlMyLink
        }
    }, function(res) {
        if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
            $("#showP").html("建立安全连接初始化成功")
            iscpConnection()
        } else {
            $("#showP").html("建立安全连接初始化失败")
        }
    });
}
// 建立连接
function iscpConnection() {
    wx.invoke("ext_ISCP_ConnectService", {
        data: {
            iscpIP: urlMyLink,
            ip: urlLinkIp,
            port: urlLinkPort,
            user: urlServeruser,
            appid: urlServerappid
        }
    }, function(res) {
        if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
            $("#showP").html("建立安全连接成功")
            iscpTransferPort()
        } else {
            $("#showP").html("建立安全连接失败")
        }
    });
}

// 获取端口
function iscpTransferPort() {
    wx.invoke("ext_ISCP_GetLocalPort", {
        data: {
            iscpIP: urlMyLink,
            ip: urlLocalip,
            port: urlLocalport
        }
    }, function(res) {
        if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
            iscp.port = res.result;
            sessionStorage.setItem("iscp_port", res.result)

            $("#showP").html("建立安全连接获取端口成功")
                // iscpState()  //感觉没用
            sessionStorage.setItem("err_msg", "err_msg")
        } else {
            $("#showP").html("建立安全连接获取端口失败")
        }
    });
}

// 连接状态
function iscpState() {
    wx.invoke("ext_ISCP_Status", {
        data: {
            iscpIP: urlMyLink
        }
    }, function(res) {
        if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
            if (res.result == "2") {
                sessionStorage.setItem("err_msg", "err_msg")
            }
        } else {
            $("#showP").html("建立安全连接失败")
        }
    });
}

// 关闭连接
function closeIscp() {
    wx.invoke("ext_ISCP_Close", {
        data: {
            iscpIP: urlMyLink
        }
    }, function(res) {
        if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {
            // $(".iscp-loading").css({
            //     "display": "none"
            // });
            // $($(".eis-step-icon").data("codeTrig", true).get(5)).click();
            // $(".eis-step-icon").removeData("codeTrig");
            //$("button").removeAttr("disabled");
        }
    });
}
/*操作日志异步公共接口  
    operatorType 1/用户登陆 、登出 2/OCR识别 
    operatorBasic  1/打印 2/手写 3/身份证 4/增值税 5/火车票    
    operatorContent 1//复制文本 2/发送邮箱 3/识别
*/

function addOperator(type, basic, content, isDel, operatorStatus, through, time, pic,competition) {
    userId = sessionStorage.getItem("userId");
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    // flagaddOperator false  为暂停操作日志
    // if (flagaddOperator == false) return
    let data = {
        "userId": userId, //用户id
        "operator": "", //操作人  现已废弃
        "operatorIP": "001", //操作ip
        "operatorType": type, //type 1：用户登录注销 2：OCR识别 3：语音识别 4：我的
        "operatorBasic": basic, //基于type 1.1：用户登录 1.2：用户注销 2.1：打印文字识别 2.2：手写文字识别 2.3：身份证识别 2.4：增值税专票识别 2.5：火车票识别 2.6：表格识别 2.7：Pdf转word 2.8：银行卡识别 2.9：增值税普票识别 2.10：工作票识别 2.11：操作票识别 2.12：出租车票识别 2.13：航空行程单识别 3.1：实时转写 3.2：语音笔记 3.3：录音转写 4.1：邮箱 4.2：安全知情同意书 
        "operatorContent": content, //基于type 1：登录、注销 2：识别、复制文本、发送邮箱、发送内网、下载文件 3：完成保存、复制、发送邮箱、发送内网 4.1：邮箱设置、邮箱查询 4.2：同意、查询 ，4.6发送验证码
        "isDel": isDel, //0：邮箱及同意书数据 1：操作数据
        "operatorStatus": operatorStatus, //操作是否成功 1成功 0失败
        "through": through, //操作失败的原因
        "duration": time, //语音使用时间 秒
        "timestamp": new Date().getTime() + "", //时间戳
        "competition": competition
    }
    data = JSON.stringify(data)
    let sign = sm3(data);
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    let addOperatorList
    let URLS
    if (pic == "picture") {
        URLS = "/photoTransfer/operator/addOperator"
    } else {
        URLS = "/tjAiAssistant/operator/addOperator"
    }
    $.ajax({
        url: localUrlLink + iscp_port + URLS,
        type: "post",
        async: true, //是否同步，false表示同步请求 true表示异步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            sign: sign,
            Authentication: AuthenticationSession,
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")
                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                    }
                } else if (res.code == 500) {
                    // mui.toast(res.resultValue, {
                    //     duration: 'long',
                    //     type: 'div'
                    // })
                } else {
                    // mui.toast("请求异常请稍后再试", {
                    //     duration: 'long',
                    //     type: 'div'
                    // })
                }

            } else {
                // mui.toast("sign验证失败", {
                //     duration: 'long',
                //     type: 'div'
                // })
            }
            addOperatorList = res
            return addOperatorList
        },
        error: (e) => {
            // mui.toast("请求异常请稍后再试", {
            //     duration: 'long',
            //     type: 'div'
            // })
        },

    });
    return addOperatorList
};
/*操作日志同步接口，只适用于知情同意书,其他接口不使用*/
function securityAgreement(type, basic, content, isDel) {
    let userId = sessionStorage.getItem("userId");
    let unitId = sessionStorage.getItem("unitId");
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    let data = {
        "userId": userId, //用户id
        "unitId": unitId, //单位id
        "timestamp": new Date().getTime() + "" //时间戳
    }
    data = JSON.stringify(data)
    let sign = sm3(data);
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    let addOperatorList
    $.ajax({
        url: localUrlLink + iscp_port + "/tjAiAssistant/securityAgreement/add",
        type: "post",
        async: false, //是否同步，false表示同步请求 true表示异步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            sign: sign,
            Authentication: AuthenticationSession,
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")

                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                    }

                } else if (res.code == 500) {
                    mui.toast(res.resultValue, {
                        duration: 'long',
                        type: 'div'
                    })
                } else {
                    mui.toast("请求异常请稍后再试", {
                        duration: 'long',
                        type: 'div'
                    })
                }
                addOperatorList = res
                return addOperatorList

            }
        },
        error: (e) => {
            mui.toast("请求异常请稍后再试", {
                duration: 'long',
                type: 'div'
            })
        },

    });
    return addOperatorList
};

// 验证邮箱
function validateMail(mail) { //校验邮箱
    var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    let ismail = reg.test(mail);
    if (!ismail) {
        return false
    } else {
        return true
    }
}
/* 发送邮箱公共接口*/
function mailbox(sceneNo, fileName, fileExt, fileContent, orgId, userId, userName, toMail, timestamp, pdf) {
    userId = sessionStorage.getItem("userId");
    orgId = sessionStorage.getItem("unitId")
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }

    // 注册邮箱发送验证码
    if (sceneNo != 41) {
        toMail = sessionStorage.getItem("toMail")
        // let validateMailFlag = validateMail(toMail)
            // 发送邮箱前判断是否注册过
        if (!toMail) {
            $(".curtain").css("display", "none")
            mui.toast('请到内网邮箱设置中设置内网邮箱！', {
                duration: 'long',
                type: 'div'
            })
            return
        }
    }
    let msgString
    let newFileContent
    if (sceneNo == 3 || sceneNo == 8) {
        msgString = fileContent + "," + sm3(fileContent)
        newFileContent = sm2.doEncrypt(msgString, sessionStorage.getItem("bpuk"), 1)
    } else {
        newFileContent = fileContent
    }

    let data = {
        // 1:打印文字识别 2:手写文字识别3:身份证识别 4:增值税专票识别 5:火车票识别 6:表格识别 7:Pdf转word 8:银行卡识别 9:增值税普票识别 10:工作票识别 11:操作票识别 12:出租车票识别 13:航空行程单识别 31:实时转写 32:语音笔记 33:录音转写
        // "sceneName": sceneName,//场景名称(身份证识别、增值税识别、火车票识别、手写文字识别、打印文字识别、pdf转word） 
        "sceneNo": sceneNo, //("1","打印文字识别"),("2", "手写文字识别"),("3", "身份证识别"),("4", "增值税专票识别"),("5", "火车票识别"),("6", "表格识别"),("7", "Pdf转word"),("8", "银行卡识别"),("9", "增值税普票识别"),
        //("10", "工作票识别"),("11", "操作票识别"),("12", "出租车票识别"),("13", "航空行程单识别"),("31", "实时转写"),("32", "语音笔记"),("33", "录音转写"),（"4,1", "我的"）
        "fileName": fileName, //文本名称
        "fileExt": fileExt, //文本后缀名称
        "fileContent": newFileContent, //识别后内容
        "orgId": orgId, //单位id
        "userId": userId, //用户id
        "userName": "", //用户名称
        "toMail": '',
        "timestamp": timestamp
    };
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    data = JSON.stringify(data)
    let sign = sm3(data);
    let mailboxReturn
    let uRL
    if (pdf == 'pdf') {
        uRL = "/tjAiAssistant/IdentificationFile/pdfSendMail"
    } else {
        uRL = "/tjAiAssistant/IdentificationFile/fileDataAdd"
    }
    $.ajax({
        url: localUrlLink + iscp_port + uRL,
        type: "post",
        async: false, //是否同步，false表示同步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            sign: sign,
            Authentication: AuthenticationSession,
        },
        success: (res, txt, xhr) => {
            mailboxReturn = res.code
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")
                if (res.code == 200) {
                    $(".curtain").css("display", "none")
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                        if (sceneNo == 41) {
                            mui.toast("验证码已发送至内网邮箱", {
                                duration:1300,
                                type: "div",
                            });
                        } else {
                            mui.toast("已发送成功", {
                                duration: "long",
                                type: "div",
                            });
                        }
                    }
                } else if (res.code == 500) {
                    $(".curtain").css("display", "none")
                    mui.toast(res.resultValue, {
                        duration: 'long',
                        type: 'div'
                    })
                } else {
                    $(".curtain").css("display", "none")
                    mui.toast('请求异常,请稍后再试', {
                        duration: 'long',
                        type: 'div'
                    })
                }
            } else {
                $(".curtain").css("display", "none")
                mui.toast("完整性校验失败", {
                    duration: "long",
                    type: "div",
                });
            }
            return mailboxReturn
        },
        error: (e) => {
            //  setTimeout(()=>{
            $(".curtain").css("display", "none")
            mui.toast('请求异常,请稍后再试', {
                    duration: 'long',
                    type: 'div'
                })
                // },2000)
        },
    });
    return mailboxReturn
};
// 语音笔记创建接口
function getaddVoice(messageTitle, message, saveType, timestamp, sceneNo) {
    userId = sessionStorage.getItem("userId");
    // userName = sm2UserName()
    // if (userName == "***") {
    //     alert("userName解密错误")
    //     return
    // }
    // let msgName = userName + "," + sm3(userName)
    // let msgUserName = sm2.doEncrypt(msgName, sessionStorage.getItem("bpuk"), 1)
    orgId = sessionStorage.getItem("unitId")
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    let data = {
        "sceneNo": sceneNo, //31:实时转写 32:语音笔记
        "messageTitle": messageTitle, //笔记标题
        "message": message, //笔记内容
        "orgId": orgId, //单位id
        "saveType": saveType, //1是完成按钮 0是发送邮箱按钮
        "userId": userId, //用户id
        "userName": "", //用户名称
        "timestamp": timestamp,
        "toMail": '', //发送给谁
    };
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    data = JSON.stringify(data)
    let sign = sm3(data);
    let getaddVoiceReturn
    $.ajax({
        url: localUrlLink + iscp_port + "/tjAiAssistant/voice/insertVoiceNotes",
        type: "post",
        async: false, //是否同步，false表示同步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            Authentication: AuthenticationSession,
            sign: sign
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")
                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                        if (saveType == 1) {
                            mui.toast('已保存', {
                                duration: 'long',
                                type: 'div'
                            })
                        } else if (saveType == 0) {
                            mui.toast('已发送成功', {
                                duration: 'long',
                                type: 'div'
                            })
                        }
                        if (sceneNo == 32 && saveType == 1) {
                            setTimeout(() => {
                                $(location).attr("href", "Voice.html");
                            }, 800)
                        } else if (sceneNo == 31 && saveType == 1) {
                            setTimeout(() => {
                                $(location).attr("href", "OnSiteShorthand.html");
                            }, 800)
                        }
                    }

                } else if (res.code == 500) {
                    mui.toast(res.resultValue, {
                        duration: 'long',
                        type: 'div'
                    })
                } else {
                    mui.toast('失败', {
                        duration: 'long',
                        type: 'div'
                    })
                }
                getaddVoiceReturn = res
                return getaddVoiceReturn

            } else {
                mui.toast('完整性校验失败', {
                    duration: 'long',
                    type: 'div'
                })
            }

        },
        error: (e) => {
            mui.toast('请求异常,请稍后再试', {
                duration: 'long',
                type: 'div'
            })
        },

    });
    return getaddVoiceReturn
}
// 语音笔记修改接口
function getreviseVoice(id, messageTitle, message, saveType, timestamp, sceneNo) {
    userId = sessionStorage.getItem("userId");
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    let data = {
        "id": id, //主键id
        "userId": userId,
        "messageTitle": messageTitle, //笔记标题
        "message": message, //笔记内容
        "saveType": saveType, //1是完成按钮 0是发送邮箱按钮
        "timestamp": timestamp,
        "toMail": '', //发送给谁
        'sceneNo': sceneNo
    };
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    data = JSON.stringify(data)
    let sign = sm3(data);
    let getreviseVoiceReturn
    $.ajax({
        url: localUrlLink + iscp_port + "/tjAiAssistant/voice/updateVoiceNotes",
        type: "post",
        async: false, //是否同步，false表示同步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            Authentication: AuthenticationSession,
            sign: sign
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")

                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                        mui.toast('已保存', {
                            duration: 'long',
                            type: 'div'
                        })
                        if (sceneNo == 32 && saveType == 1) {
                            setTimeout(() => {
                                $(location).attr("href", "Voice.html");
                            }, 800)
                        } else if (sceneNo == 31 && saveType == 1) {
                            setTimeout(() => {
                                $(location).attr("href", "OnSiteShorthand.html");
                            }, 800)
                        }
                    }
                } else if (res.code == 500) {
                    mui.toast(res.resultValue, {
                        duration: 'long',
                        type: 'div'
                    })
                } else {
                    mui.toast('失败', {
                        duration: 'long',
                        type: 'div'
                    })
                }


            } else {
                mui.toast('完整性校验失败', {
                    duration: 'long',
                    type: 'div'
                })
            }
            getreviseVoiceReturn = res
            return getreviseVoiceReturn;

        },
        error: (e) => {
            mui.toast('请求异常,请稍后再试', {
                duration: 'long',
                type: 'div'
            })
        },

    });
    return getreviseVoiceReturn
};
// 语音列表接口
// function shorthandListPost(sceneNo) {
//     userId = sessionStorage.getItem("userId");
//     orgId = sessionStorage.getItem("unitId")
//     if (sessionStorage.getItem("iscp_port")) {
//         iscp_port = sessionStorage.getItem("iscp_port");
//     } else {
//         iscp_port = ""
//     }
//     let data = {
//         "orgId": orgId, //单位id
//         "userId": userId, //用户id
//         "sceneNo": sceneNo, //31:实时转写 32:语音笔记
//         "timestamp": new Date().getTime() + ""
//     };
//     data = JSON.stringify(data)
//     let sign = sm3(data);

//     let AuthenticationSession = sessionStorage.getItem("Authentication");
//     var arr
//     $.ajax({
//         url: localUrlLink + iscp_port + "/tjAiAssistant/voice/queryVoiceNotes",
//         type: "post",
//         async: false, //是否同步，false表示同步请求
//         dataType: "json",
//         data: data,
//         headers: {
//             "Content-Type": "application/json;charset=UTF-8",
//             Authentication: AuthenticationSession,
//             sign: sign
//         },
//         success: (res, txt, xhr) => {
//             let sm3res = JSON.stringify(res)
//             if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
//                 let Authentication = xhr.getResponseHeader("Authentication")

//                 if (res.code == 200) {
//                     if (Authentication) {
//                         sessionStorage.setItem("Authentication", Authentication);
//                     }
//                 } else if (res.code == 500) {
//                     mui.toast(res.resultValue, {
//                         duration: 'long',
//                         type: 'div'
//                     })
//                 } else {
//                     mui.toast('请求异常,请稍后再试', {
//                         duration: 'long',
//                         type: 'div'
//                     })
//                 }
//                 arr = res
//                 return arr

//             } else {
//                 mui.toast('完整性校验失败', {
//                     duration: 'long',
//                     type: 'div'
//                 })
//             }
//         },
//         error: (e) => {
//             mui.toast('请求异常,请稍后再试', {
//                 duration: 'long',
//                 type: 'div'
//             })
//         },

//     });
//     return arr
// }
// 语音删除功能
function shorthandDelete(id, sceneNo) {
    userId = sessionStorage.getItem("userId");
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    let data = {
        "id": id, //单位id
        "userId": userId,
        "sceneNo": sceneNo, //31:实时转写 32:语音笔记
        "timestamp": new Date().getTime() + ""
    };
    data = JSON.stringify(data)
    let sign = sm3(data);
    let resResult
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    $.ajax({
        url: localUrlLink + iscp_port + "/tjAiAssistant/voice/deleteVoiceNotes",
        type: "post",
        async: false, //是否同步，false表示同步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            Authentication: AuthenticationSession,
            sign: sign
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")

                if (res.code == 200) {
                    if (Authentication) {
                        $(".curtain").css("display", "none");
                        sessionStorage.setItem("Authentication", Authentication);
                        mui.toast('已删除', {
                            duration: "long",
                            type: 'div'
                        })
                    }
                } else if (res.code == 500) {
                    $(".curtain").css("display", "none");
                    mui.toast(res.resultValue, {
                        duration: "long",
                        type: 'div'
                    })
                } else {
                    $(".curtain").css("display", "none");
                    mui.toast('请求异常,请稍后再试', {
                        duration: "long",
                        type: 'div'
                    })
                }
                resResult = res.resultValue
                return resResult

            } else {
                $(".curtain").css("display", "none");
                mui.toast('完整性校验失败', {
                    duration: 'long',
                    type: 'div'
                })
            }
        },
        error: (e) => {
            $(".curtain").css("display", "none");
            mui.toast('请求异常,请稍后再试', {
                duration: 'long',
                type: 'div'
            })
        },
    });
    return resResult
}


// 退出断开会话
function IscLogout() {
    userId = sessionStorage.getItem("userId");
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    let data = {
        "userId": userId, //单位id
        "timestamp": new Date().getTime() + ""
    };
    data = JSON.stringify(data)
    let sign = sm3(data);
    let resResult
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    $.ajax({
        url: localUrlLink + iscp_port + "/tjAiAssistant/isc/logout",
        type: "post",
        async: false, //是否同步，false表示同步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            Authentication: AuthenticationSession,
            sign: sign
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")

                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                    }


                } else if (res.code == 500) {
                    mui.toast(res.resultValue, {
                        duration: 'long',
                        type: 'div'
                    })
                } else {
                    mui.toast("请求异常请稍后再试", {
                        duration: 'long',
                        type: 'div'
                    })
                }
                resResult = res
                return resResult
            } else {
                mui.toast('完整性校验失败', {
                    duration: 'long',
                    type: 'div'
                })
            }
        },
        error: (e) => {
            if (e.status == "9981") {
                mui.toast('当前用户会话过期,将要自动跳转登录页面!', {
                    duration: 'long',
                    type: 'div'
                })
                setTimeout(function() {
                    $(location).attr("href", "../index.html");
                }, 1000)
            }
        },
    });
    return resResult
}

/**
 * 获取当前积分 次数等信息
 * sceneNo 操作类型
 * time 使用次数 或者 使用秒数
 * 前端：根据时间段，分配次数，积分规则：
 * 0-200   5次ocr识别，语音识别10分钟。
 * 200-500  10次 ocr识别 语音20分钟。
 * 500-2000  20次ocr识别，语音40分钟。
 * 2000-5000  30次ocr识别，语音识别60分钟。
 * 5000-10000  50次 ocr识别 语音120分钟
 * 10000以上   80次 ocr识别  语音180分钟
 *
 * "operatorType": type, //type 1：用户登录注销 2：OCR识别 3：语音识别 4：我的
 * "operatorBasic": basic, //基于type 1.1：用户登录 1.2：用户注销 2.1：打印文字识别 2.2：手写文字识别 2.3：身份证识别 2.4：增值税专票识别 2.5：火车票识别 2.6：表格识别 2.7：Pdf转word 2.8：银行卡识别 2.9：增值税普票识别 2.10：工作票识别 2.11：操作票识别 2.12：出租车票识别 2.13：航空行程单识别 3.1：实时转写 3.2：语音笔记 3.3：录音转写 4.1：邮箱 4.2：安全知情同意书 
 *
 * */
function Integral(operatorType, time) {
    time = Number(time)
        // 获取剩余ocr次数和剩余时间
    let integralTotal = JSON.parse(sessionStorage.getItem("integralTotal"))
    if (operatorType == 2) {
        // ocr
        integralTotal.ocr = integralTotal.ocr - time
    } else if (operatorType == 3) {
        // 语音
        integralTotal.time = integralTotal.time - time
        integralTotal.timeDivide = (integralTotal.time / 60).toFixed(0)
    } else if (operatorType == 5) {
        let integral = Number(sessionStorage.getItem("integral"))
        sessionStorage.setItem("integral", integral + time)
            // 加分后 更新ocr次数 语音识别时间
        integralTotal = ScoreLevel(integral, integralTotal.ocrInte - integralTotal.ocr, integralTotal.timeInte * 60 - integralTotal.time)
    }
    sessionStorage.setItem("integralTotal", JSON.stringify(integralTotal))
}

// 计算剩余 次数 时间 初始化
function ScoreLevel(integral, ocrFrequency, voiceTime) {
    // let integral = sessionStorage.getItem("integral");//登录后当前积分
    // let ocrFrequency = sessionStorage.getItem("ocrFrequency");//ocr已使用次数
    // let voiceTime = sessionStorage.getItem("voiceTime");//语音已使用时间
    // let upSampleFre = sessionStorage.getItem("upSampleFre");//当日上传样本次数
    // let upTotalSampleFre = sessionStorage.getItem("upTotalSampleFre");//累计上传样本次数
    // let integralRanking = sessionStorage.getItem("integralRanking");//积分排名
    let data
    if (integral < 200) {
        return data = {
            ocr: 5 - ocrFrequency,
            time: 600 - voiceTime,
            ocrInte: 5,
            timeInte: 10,
            timeDivide: ((600 - voiceTime) / 60).toFixed(0)
        };
    }
    if (integral < 500) {
        return data = {
            ocr: 10 - ocrFrequency,
            time: 1200 - voiceTime,
            ocrInte: 10,
            timeInte: 20,
            timeDivide: ((1200 - voiceTime) / 60).toFixed(0)
        };
    }
    if (integral < 2000) {
        return data = {
            ocr: 20 - ocrFrequency,
            time: 2400 - voiceTime,
            ocrInte: 20,
            timeInte: 40,
            timeDivide: ((2400 - voiceTime) / 60).toFixed(0)
        };
    }
    if (integral < 5000) {
        return data = {
            ocr: 30 - ocrFrequency,
            time: 3600 - voiceTime,
            ocrInte: 30,
            timeInte: 60,
            timeDivide: ((3600 - voiceTime) / 60).toFixed(0)
        };
    }
    if (integral < 10000) {
        return data = {
            ocr: 50 - ocrFrequency,
            time: 7200 - voiceTime,
            ocrInte: 50,
            timeInte: 120,
            timeDivide: ((7200 - voiceTime) / 60).toFixed(0)
        };
    }
    return data = {
        ocr: 80 - ocrFrequency,
        time: 10800 - voiceTime,
        ocrInte: 80,
        timeInte: 180,
        timeDivide: ((10800 - voiceTime) / 60).toFixed(0)
    };
}


// 解密姓名
function sm2UserName() {
    let newUserName
    let userNameString = sm2.doDecrypt(sessionStorage.getItem("userName"), sessionStorage.getItem("fprk"), 1)
    let userNameList = userNameString.split(",");
    if (sm3(userNameList[0]) == userNameList[1]) {
        newUserName = userNameList[0]
        return newUserName
    } else {
        return "***"
    }
}
// 手机号脱敏 11位手机号中间四位脱敏显示，例如：187****1234
function noPassByMobile(str) {
    if (null != str && str != undefined) {
        var pat = /(\d{3})\d*(\d{4})/;
        return str.replace(pat, '$1****$2');
    } else {
        return "";
    }
}

// 姓名脱敏 
/**
 * 姓名脱敏处理，规则：3个字以内脱敏第一个字，4—6个字脱敏前两个字，大于6个字脱敏第3—6个字，示例：张三（三）、张三水（三水）、长孙无忌（**无忌）、罗斯托罗司机格（罗斯XXXX格）
 * 
 * 
 */
function noPassByName(str) {
    if (null != str && str != undefined) {
        if (str.length == 2) {
            return str.substring(0, 1) + '*' //截取name 字符串截取第一个字符，
        } else if (str.length == 3) {
            return str.substring(0, 1) + "*" + str.substring(2, 3) //截取第一个和第三个字符
        } else if (str.length > 3) {
            return str.substring(0, 1) + "*" + '*' + str.substring(3, str.length) //截取第一个和大于第4个字符
        }
    } else {
        return "";
    }
}

// 身份证脱敏
function noPassIdCard(str) {
    if (!!str) {
        return str.replace(/(\w{4})\w*(\w{4})/, '$1********$2');
    } else {
        return ""
    }
}

// 银行卡脱敏
function noPassBankCard(str) {
    if (!!str && str.length > 8) {
        return `${str.substring(0, 4)} ${"*".repeat(str.length - 8).replace(/(.{4})/g, `
        $1 `)}${str.length % 4 ? " " : ""}${str.slice(-4)}`;
    } else {
        return ""
    }
}
